package cn.tinlan.shopcoin.app.home;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.zackratos.ultimatebar.UltimateBar;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.CallClazzProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;
import com.zhouyou.http.subsciber.BaseSubscriber;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.tinlan.shopcoin.MainActivity;
import cn.tinlan.shopcoin.R;
import cn.tinlan.shopcoin.Utils.GlideImageLoader;
import cn.tinlan.shopcoin.Utils.SPUtils;
import cn.tinlan.shopcoin.Utils.ToastUtils;
import cn.tinlan.shopcoin.Utils.Tools;
import cn.tinlan.shopcoin.app.car.CarActivity;
import cn.tinlan.shopcoin.app.discover.DiscoverActivity;
import cn.tinlan.shopcoin.app.discover.classify.ClassifyActivity;
import cn.tinlan.shopcoin.app.discover.classify.model.GoodsCategoryDetailModel;
import cn.tinlan.shopcoin.app.gooddetail.GoodDetailActivity;
import cn.tinlan.shopcoin.app.home.Model.HomeBannerModel;
import cn.tinlan.shopcoin.app.home.Model.IconTitleModel;
import cn.tinlan.shopcoin.app.home.Model.ShopModel;
import cn.tinlan.shopcoin.app.home.Views.HomeAdsView;
import cn.tinlan.shopcoin.app.home.Views.HomeBrandAdsView;
import cn.tinlan.shopcoin.app.home.adapter.LittleModuleAdapter;
import cn.tinlan.shopcoin.app.home.adapter.ShopListAdapter;
import cn.tinlan.shopcoin.app.home.decoration.HomeGridDecoration;
import cn.tinlan.shopcoin.app.koi.model.KoiNoticeModel;
import cn.tinlan.shopcoin.app.search.SearchActivity;
import cn.tinlan.shopcoin.app.web.WebActivity;
import cn.tinlan.shopcoin.base.BaseFragment;
import cn.tinlan.shopcoin.base.CustomApiResult;
import cn.tinlan.shopcoin.widget.category.Constants;
import cn.tinlan.shopcoin.widget.custompop.BaseNiceDialog;
import cn.tinlan.shopcoin.widget.custompop.DialogViewHolder;
import cn.tinlan.shopcoin.widget.custompop.NiceDialog;
import cn.tinlan.shopcoin.widget.custompop.ViewConvertListener;
import io.reactivex.Observable;
import pub.devrel.easypermissions.EasyPermissions;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Mortimer on 2018/11/20. 14:46
 * 佛祖🙏，永无bug。
 */
public class HomeFragment extends BaseFragment implements EasyPermissions.PermissionCallbacks{

    @BindView(R.id.search_tv)
    TextView searchTV;
    @BindView(R.id.home_right_car)
    ImageView shoppingCar;
    @BindView(R.id.home_banner)
    Banner banner;
    //小模块GridView布局
    @BindView(R.id.recyclerview_little_module)
    RecyclerView littleModuleRecyclerView;
    //4块广告封装成的自定义View
    @BindView(R.id.home_ads_view)
    HomeAdsView homeAdsView;
    //4快品牌广告
    @BindView(R.id.home_brand_view)
    HomeBrandAdsView homeBrandAdsView;
    //团购商店列表
    @BindView(R.id.recycler_view_shops)
    RecyclerView rvShopList;
    //下拉刷新组件
    @BindView(R.id.smartRefreshLayout_home)
    SmartRefreshLayout smartRefreshLayout;


    private ShopListAdapter mShopListAdapter;
    private List<GoodsCategoryDetailModel> mShopModels = Collections.emptyList();
    private List<HomeBannerModel> bannerModels;

    public static final int PERMISSIONS_CODE_1 = 201;
    private int page = 1;
    /**
     * 需要的权限
     */
    private String[] mPerms = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.READ_PHONE_STATE,Manifest.permission.REQUEST_INSTALL_PACKAGES};


//    @Nullable
//    @Override
//    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
////        View homeView = inflater.inflate(R.layout.fragment_home,null);
//
//        if (rootView == null) {
//            rootView = inflater.inflate(R.layout.fragment_home, container,false);
//
//        }
//        //绑定 ButterKnife
//        ButterKnife.bind(this, rootView);
//
//        return  rootView;
//    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        drawableBar(ContextCompat.getDrawable(getActivity(),R.color.redNaV));

    }

    @Override
    protected void onFragmentFirstVisible() {
//        init();

//        drawableBar(ContextCompat.getDrawable(getActivity(),R.color.redNaV));
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void loadData() {

    }

//    @Override
//    protected void onFragmentVisibleChange(boolean isVisible) {
//
//    }

    @Override
    public void initView(View rootView) {
//        super.initView(rootView);
        initNaView();
        initBanner();
        initLittleModuleRecyclerView();
        initAds();
        initBrands();
        initShopList();
        initSmartRefreshLayout();
        requestPermissions();
    }

    @Override
    public void initData() {
        super.initData();
        page = 1;
        loadNewNotice();
        loadBannerData();
        getHomeListData(page,0,0);
    }

    private void drawableBar (Drawable drawable) {
        UltimateBar.Companion.with(getActivity())
                .statusDrawable(drawable)
                .applyNavigation(true)
                .navigationDrawable(drawable)
                .create()
                .drawableBar();
    }

    private void initSmartRefreshLayout() {
        smartRefreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        smartRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));
        smartRefreshLayout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        smartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                refreshLayout.finishLoadMore();      //加载完成
//                refreshLayout.finishLoadMoreWithNoMoreData();  //全部加载完成,没有数据了调用此方法
                page++;
                getHomeListData(page,0,0);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

//                Log.d("test->>>","刷新完成");
                //请求数据
//                refreshLayout.finishRefresh();  //刷新完成
                page = 1;
                loadBannerData();
                getHomeListData(page,0,0);
            }
        });

    }

    private void initNaView() {
        searchTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(mActivity, SearchActivity.class));
            }
        });

        shoppingCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ToastUtils.show("功能暂无，敬请期待");
//                startActivity(new Intent(mActivity, CarActivity.class));
            }
        });
    }


    private void initShopList() {
//        LinearLayoutManager lm = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false) {
//            @Override
//            public boolean canScrollVertically() {
//                return false;
//            }
//        };


        GridLayoutManager gm = new GridLayoutManager(getActivity(),2,GridLayoutManager.VERTICAL,false) {

            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

//        List<ShopModel> datas = new ArrayList<>();
//        for (int i = 0 ; i< 2; i++){
//            datas.add(new ShopModel(R.drawable.ads_1,""));
//        }
//        mShopModels = new ArrayList<>();
        rvShopList.setLayoutManager(gm);
//        rvShopList.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        rvShopList.setItemAnimator(new DefaultItemAnimator());
        mShopListAdapter = new ShopListAdapter(getActivity(), R.layout.view_home_item, mShopModels);
//        mShopListAdapter.setUpFetchEnable(true);
        mShopListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GoodsCategoryDetailModel goodsCategoryDetailModel =(GoodsCategoryDetailModel)adapter.getItem(position);
                Intent intent = new Intent(mActivity, GoodDetailActivity.class);
                intent.putExtra("goods_id",goodsCategoryDetailModel.getId());
                intent.putExtra("title",goodsCategoryDetailModel.getName());
                startActivity(intent);
            }
        });
        rvShopList.setAdapter(mShopListAdapter);

        Log.i("test>>>>","zoule");


    }

    public void setShopListData(List<GoodsCategoryDetailModel> shopModels) {
        mShopListAdapter.setNewData(shopModels);
    }

    private void initBrands() {
        homeBrandAdsView.setOnAdsClickListener(new HomeBrandAdsView.OnBrandAdsClickListener() {
            @Override
            public void onBrandAds1Click() {

            }

            @Override
            public void onBrandAds2Click() {

            }

            @Override
            public void onBrandAds3Click() {

            }

            @Override
            public void onBrandAds4Click() {

            }
        });
    }

    private void initAds() {
        homeAdsView.setOnAdsClickListener(new HomeAdsView.OnAdsClickListener() {
            @Override
            public void onAds1Click() {
//                startActivity(new Intent(mActivity, GoodDetailActivity.class));
            }

            @Override
            public void onAds2Click() {

            }

            @Override
            public void onAds3Click() {

            }

            @Override
            public void onAds4Click() {

            }
        });
    }

    //设置分类
    private void initLittleModuleRecyclerView() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),4);
        //设置LayoutManager
        littleModuleRecyclerView.setLayoutManager(gridLayoutManager);
        //设置分割器
        littleModuleRecyclerView.addItemDecoration(new HomeGridDecoration(6));
        //设置动画
        littleModuleRecyclerView.setItemAnimator(new DefaultItemAnimator());

        final List<IconTitleModel> datas = new ArrayList<>();
        datas.add(new IconTitleModel(R.drawable.classfiy_icon, "全部分类"));
        datas.add(new IconTitleModel(R.drawable.signin_icon, "签到"));
        datas.add(new IconTitleModel(R.drawable.homepage2, "周边游"));
        datas.add(new IconTitleModel(R.drawable.homepage3, "机票/火车票"));
        datas.add(new IconTitleModel(R.drawable.homepage4, "丽人/美发"));
        datas.add(new IconTitleModel(R.drawable.homepage5, "旅游/出行"));
        datas.add(new IconTitleModel(R.drawable.homepage6, "跑腿/代购"));
        datas.add(new IconTitleModel(R.drawable.homepage7, "景点/门票"));
        //设置Adapter
        LittleModuleAdapter littleModuleAdapter = new LittleModuleAdapter(
                R.layout.view_icon_title_small, datas);
        littleModuleRecyclerView.setAdapter(littleModuleAdapter);

        //设置item点击事件
        littleModuleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {


                switch (position){
                    case 0:
                        startActivity(new Intent(mActivity, DiscoverActivity.class));
                        break;
                    case 1:
                        if (SPUtils.getIsLogin(mActivity)) {
                            isSignInDCC();
                        }else {
                            ToastUtils.show("请先登录");
                        }
                        break;
                }

//                ToastUtils.show(datas.get(position).getTitle());
            }
        });
    }

    //设置轮播图
    private void initBanner() {
//        List<Integer> mBannerImages = new ArrayList<>();
//        mBannerImages.add(R.drawable.banner);
//        mBannerImages.add(R.drawable.banner);
//        mBannerImages.add(R.drawable.banner);
//        mBannerImages.add(R.drawable.banner);
//        mBannerImages.add(R.drawable.banner);
//        mBannerImages.add(R.drawable.banner);

        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                .setImageLoader(new GlideImageLoader())
                .setBannerAnimation(Transformer.Default)
                .isAutoPlay(true)
                .setDelayTime(3000)
                .setIndicatorGravity(BannerConfig.CENTER)
                .start();

        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent(mActivity, WebActivity.class);
                intent.putExtra("title",bannerModels.get(position).getName());
                intent.putExtra("type",1);
                intent.putExtra("webUrl",bannerModels.get(position).getJump_url());
                startActivity(intent);

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        banner.stopAutoPlay();
    }


    /**
     * 拍照
     */
    private void requestPermissions() {

        Tools.checkAppUp();
        // 判断权限
        if (EasyPermissions.hasPermissions(mActivity, mPerms)) {


        } else {
            // 如果用户拒绝权限，第二次打开才会显示提示文字
//            EasyPermissions.requestPermissions(this, "使用app更新等功能，需要这些权限", PERMISSIONS_CODE_1, mPerms);
        }
    }



//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
//        LogUtils.i("onPermissionsGranted: " + "同意授权");
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        ToastUtils.show("没有权限可能会引起程序崩溃");

        /**
         * 跳转到 APP 详情的权限设置页
         *
         * 可根据自己的需求定制对话框，点击某个按钮在执行下面的代码
         */
//        Intent intent = Util.getAppDetailSettingIntent(PhotoFromSysActivity.this);
//        startActivity(intent);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }



    private void loadBannerData() {
        Observable<List<HomeBannerModel>> observable = EasyHttp.get(Constants.HomeBanner)
                .execute(new CallClazzProxy<CustomApiResult<List<HomeBannerModel>>, List<HomeBannerModel>>(new TypeToken<List<HomeBannerModel>>() {}.getType()) {
                });

        observable.subscribe(new BaseSubscriber<List<HomeBannerModel>>() {
            @Override
            public void onError(ApiException e) {


            }

            @Override
            public void onNext(List<HomeBannerModel> HomeBannerModels) {
                super.onNext(HomeBannerModels);
                if (bannerModels == null ){
                    bannerModels = new ArrayList<>();
                }
                bannerModels = HomeBannerModels;
                List<String> urls = new ArrayList<>();
                for (int i=0;i<HomeBannerModels.size();i++) {
                    urls.add(Constants.IMGURL+HomeBannerModels.get(i).getThumb());
                }
                banner.update(urls);
            }
        });

    }


    private void getHomeListData(final int page1, int sort_price, int sort_sale) {

        HttpParams params = new HttpParams();
       // params.put("cate_id",goodCategoryId);
        params.put("page",page1+"");
        if (sort_price > 0){
            params.put("sort_price",sort_price+"");
        }
        if (sort_sale > 0){
            params.put("sort_sale",sort_sale+"");
        }


        Observable<List<GoodsCategoryDetailModel>> observable = EasyHttp.get(Constants.GoodCategoryDetail)
                .params(params)
                .execute(new CallClazzProxy<CustomApiResult<List<GoodsCategoryDetailModel>>, List<GoodsCategoryDetailModel>>(new TypeToken<List<GoodsCategoryDetailModel>>() {}.getType()) {
                });

        observable.subscribe(new BaseSubscriber<List<GoodsCategoryDetailModel>>() {
            @Override
            public void onError(ApiException e) {

                if (page > 1){
                    page--;
                }else {
                    page = 1;
                }

                ToastUtils.show("数据请求失败");

            }

            @Override
            public void onNext(List<GoodsCategoryDetailModel> goodsCategoryDetailModels) {
                super.onNext(goodsCategoryDetailModels);
                if (page1 == 1){
                    mShopModels = goodsCategoryDetailModels;
                    mShopListAdapter.setNewData(mShopModels);
                    smartRefreshLayout.finishRefresh();

//                    mShopListAdapter.notifyDataSetChanged();
                }else {
                    mShopListAdapter.addData(goodsCategoryDetailModels);
                    if (goodsCategoryDetailModels.size() < 16) {
                        smartRefreshLayout.finishLoadMoreWithNoMoreData();  //全部加载完成,没有数据了调用此方法
                        if (goodsCategoryDetailModels.size() < 1) {
                            if (page > 1){
                                page--;
                            }else {
                                page = 1;
                            }
                        }
                    }else {
                        smartRefreshLayout.finishLoadMore();      //加载完成
                    }

//
                }

            }
        });
    }

    private void showDialog(final String title ,final String content1) {


        FragmentManager fragmentManager = getFragmentManager();
        if (fragmentManager != null) {
            NiceDialog.init()
                    .setLayoutId(R.layout.view_koi_notice)
                    .setConvertListener(new ViewConvertListener() {
                        @Override
                        protected void convertView(DialogViewHolder holder, final BaseNiceDialog dialog) {

                            TextView notice =  holder.getView(R.id.notice_content_title);
                            WebView webView = holder.getView(R.id.notice_c_c);
                            notice.setText(title);
                            webView.loadData(content1,"text/html;charset=utf-8","utf-8");
//                        content.setText(content1);
                            holder.setOnClickListener(R.id.notice_right_close, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    dialog.dismiss();
                                }
                            });
                        }
                    })
                    .setOutCancel(false)
                    .show(fragmentManager);
        }



    }




    private void loadNewNotice() {
        EasyHttp.get(Constants.KoiNoticeNews)
                .execute(new CallBackProxy<CustomApiResult<KoiNoticeModel>, KoiNoticeModel>(new SimpleCallBack<KoiNoticeModel>() {
                    @Override
                    public void onError(ApiException e) {
//                        ToastUtils.show("添加失败");

                    }

                    @Override
                    public void onSuccess(KoiNoticeModel koiNoticeModel) {

                        showDialog(koiNoticeModel.getTitle(),koiNoticeModel.getContent());
//                        ToastUtils.show("添加成功");
                    }
                }) {
                });
    }



    private void isSignInDCC() {
        EasyHttp.get(Constants.KoiIsSignIn)
                .params("user_id", SPUtils.getUserID(mActivity))
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
//                        ToastUtils.show("添加失败");
                    }

                    @Override
                    public void onSuccess(String s) {

                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String type = jsonObject.getString("data");
                            if (type.equals("2")) {
                                signInDCC();
                            } else {
                                ToastUtils.show("已签到");
                            }
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
//                        ToastUtils.show("添加成功");
                    }
                }) {
                });
    }
    private void signInDCC() {
        EasyHttp.post(Constants.KoiSignIn)
                .params("user_id", SPUtils.getUserID(mActivity))
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
//                        ToastUtils.show("添加失败");
                    }

                    @Override
                    public void onSuccess(String s) {

                        ToastUtils.show("签到成功");
                    }
                }) {
                });
    }



}
